package com.appointment.pay.rest.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by serv on 2014/8/20.
 */
public abstract class SignUtils {
    
    private final static Logger LOGGER = LoggerFactory.getLogger(SignUtils.class);
    
    private static ThreadLocal<String> threadLocalKey = new ThreadLocal<String>();
    
    protected SignUtils() {
    }
    
    public static void setKey(String key) {
        threadLocalKey.set(key);
    }
    
    /**
     * 微信支付签名算法sign
     * 
     * @param characterEncoding
     * @param parameters
     * @param key 密钥
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    
    /**
     * 生产6位随机字符串
     * 
     * @return
     */
    public static String createValidateCode() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }
    
    /**
     * 生成20位的交易订单号，格式：yyyyMMddHHmmss+6为随机数
     * 
     * @return
     */
    public static String createOutTradeNo() {
        return DateUtils.printNow() + createValidateCode();
    }
    
    /*
     * public static String getLocalIP() { InetAddress addr = null; try { addr = InetAddress.getLocalHost(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); }
     * 
     * byte[] ipAddr = addr.getAddress(); String ipAddrStr = ""; for (int i = 0; i < ipAddr.length; i++) { if (i > 0) { ipAddrStr += "."; } ipAddrStr += ipAddr[i] & 0xFF; } // System.out.println(ipAddrStr); return ipAddrStr; }
     */
    
    public static String getLocalIP() {
        String sIP = "";
        InetAddress ip = null;
        try {        
            boolean bFindIP = false;
            Enumeration<NetworkInterface> netInterfaces =
                (Enumeration<NetworkInterface>)NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bFindIP) {
                    break;
                }
                NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
                // 遍历所有ip
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = (InetAddress)ips.nextElement();
                    if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
                        && ip.getHostAddress().indexOf(":") == -1) {
                        bFindIP = true;
                        break;
                    }
                }              
            }          
        }
        catch (Exception e) {          
            e.printStackTrace();           
        }
        
        if (null != ip) {           
            sIP = ip.getHostAddress();           
        }      
        return sIP;       
    }
    
}
